package com.desaysv.hicar

import android.content.Context
import android.os.Build
import android.os.Bundle

/**
 * @author linzi
 * @date 2023-3-27
 */
object FragmentStateFixer {
    private val modelListStr = "all" //这里可以搞成可配置机型

    fun fixState(context: Context, bundle: Bundle?) {
        if (bundle != null && checkCondition(context)) {
            bundle.classLoader = context.javaClass.classLoader
            // 9.22新增：需要修改的是bundle下androidx.lifecycle.BundlableSavedStateRegistry.key中子项的classloader
            bundle.getBundle("androidx.lifecycle.BundlableSavedStateRegistry.key")?.let {
                it.keySet()?.forEach { key ->
                    (it.get(key) as? Bundle)?.classLoader = context.javaClass.classLoader
                }
            }
        }
    }

    private fun checkCondition(context: Context): Boolean {
        if (Build.VERSION.SDK_INT != 29 && Build.VERSION.SDK_INT != 28) {
            // 只对9和10的机器进行修正
            return false
        }
        if (modelListStr == "all") {
            return true
        }
        val modelList = modelListStr.split(",")
        return modelList.contains(Build.MODEL)
    }
}